home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / osr5 / sco / scripts / admin / ftplog < prev    next >
Encoding:
AWK Script  |  1997-08-26  |  32.7 KB  |  915 lines

  1. #!/usr/local/bin/gawk -f
  2. # @(#) ftplog.gawk 1.0 97/01/28
  3. # 94/03/25 John H. DuBois III (john@armory.com)
  4. # 94/04/03 Added w and h options.
  5.  
  6. # use gawk so filename of /dev/stdin can be given.
  7.  
  8. # Expects /usr/adm/xferlog to have lines in this format:
  9. # Fri Mar 25 14:29:11 1994 5 si.UCSC.EDU 33416 /u/prologic/toolbox6.1 a _ o r prologic ftp 0 *
  10.  
  11. #current-time   transfer-time   remote-host   file-size   filename
  12. #    1-5        6        7    8        9
  13. #transfer-type   special-action-flag   direction   access-mode   username
  14. #    10        11        12        13        14
  15. #service-name   authentication-method   authenticated-user-id
  16. #    15        16            17
  17.  
  18.  
  19. BEGIN {
  20.     Name = "ftplog"
  21.     Usage = "Usage: " Name " [-hl] [-w<width>] [logfile ...]"
  22.     ARGC = Opts(Name,Usage,"hlw<",0)
  23.     deflog = "/usr/adm/xferlog"
  24.     if ("h" in Options) {
  25.     printf \
  26. "%s: Generate transfer report from wuftpd logfile.\n"\
  27. "%s\n"\
  28. "For each file transferred, a line is printed detailing the number of times\n"\
  29. "it was transferred, the time of the last transfer, the remote host and\n"\
  30. "user who did the last transfer, and the filename.\n"\
  31. "Output is sorted by the number of times each file was transferred.\n"\
  32. "If no logfiles are given, " deflog " is processed.\n"\
  33. "Options:\n"\
  34. "-h: print this help.\n"\
  35. "-l: print a more detailed report that includes the total transfer time for\n"\
  36. "each file and the size of the file.  Less space on the line is allocated\n"\
  37. "to the last host and user field to make room for this.\n"\
  38. "-w0: wide report.  No fields are truncated.\n",
  39.     Name,Usage
  40.     Err = "0"
  41.     exit 0
  42.     }
  43.     if (ARGC < 2) {
  44.     ARGC = 2
  45.     ARGV[1] = deflog
  46.     }
  47. }
  48.  
  49. NR == 1 {
  50.     StartDate = Date()
  51. }
  52.  
  53. # Only care about outgoing anonymous xfers from /pub/
  54. $13 == "a" && $12 == "o" && $9 ~ /^\/pub\// {
  55.     Name = substr($9,6)
  56.     Time[Name] += $6
  57.     Size[Name] = $8
  58.     Count[Name]++
  59.     User[Name] = $7 ":" $14
  60.     EndDate = XferDate[Name] = Date()
  61. }
  62.  
  63. END {
  64.     if (Err != "")
  65.     exit Err
  66.     Num = qsortArbIndByValue(Count,k)
  67.     printf "Outgoing anonymous ftp transfers from /pub, %s to %s.\n",
  68.     StartDate,EndDate
  69.     MaxCount= Count[k[Num]]
  70.     for (Name in Size) {
  71.     if (Size[Name] > MaxSize)
  72.         MaxSize = Size[Name]
  73.     if (Time[Name] > MaxTime)
  74.         MaxTime = Time[Name]
  75.     }
  76. #    printf "MaxSize: %s; MaxTime: %s; MaxCount: %s\n",MaxSize,MaxTime,MaxCount
  77.     CountLen = max(length(sprintf("%s",MaxCount)),3)
  78.     TimeLen = max(length(sprintf("%s",MaxTime)),4)
  79.     SizeLen = max(length(sprintf("%s",MaxSize)),4)
  80.     if (Long = ("l" in Options)) {
  81.     UserLen = 18
  82.     Format = \
  83.     "%" CountLen "s %" TimeLen "s %" SizeLen "s  %12s  %-" UserLen "s %s\n"
  84.     printf Format,"Num","Time","Size","Last Xfer","Last Host:User","File"
  85.     }
  86.     else {
  87.     UserLen = 33
  88.     Format = \
  89.     "%" CountLen "s %12s  %-" UserLen "s %s\n"
  90.     printf Format,"Num","Last Xfer","Last Host:User","File"
  91.     }
  92.     if ("w" in Options)
  93.     UserLen = 1000
  94.     for (i = Num; i >= 1; i--) {
  95.     Name = k[i]
  96.     if (Long)
  97.         printf Format,Count[Name],Time[Name],Size[Name],XferDate[Name],
  98.         substr(User[Name],1,UserLen),Name
  99.     else
  100.         printf Format,Count[Name],XferDate[Name],
  101.         substr(User[Name],1,UserLen),Name
  102.     }
  103. }
  104.  
  105. function Date() {
  106.     return sprintf("%s %2d %5s",$2,$3,substr($4,1,5))
  107. }
  108.  
  109. function max(a,b) {
  110.     if (a > b)
  111.     return a
  112.     else
  113.     return b
  114. }
  115.  
  116. ### Start of ProcArgs library
  117. # @(#) ProcArgs 1.11 96/12/08
  118. # 92/02/29 john h. dubois iii (john@armory.com)
  119. # 93/07/18 Added "#" arg type
  120. # 93/09/26 Do not count -h against MinArgs
  121. # 94/01/01 Stop scanning at first non-option arg.  Added ">" option type.
  122. #          Removed meaning of "+" or "-" by itself.
  123. # 94/03/08 Added & option and *()< option types.
  124. # 94/04/02 Added NoRCopt to Opts()
  125. # 94/06/11 Mark numeric variables as such.
  126. # 94/07/08 Opts(): Do not require any args if h option is given.
  127. # 95/01/22 Record options given more than once.  Record option num in argv.
  128. # 95/06/08 Added ExclusiveOptions().
  129. # 96/01/20 Let rcfiles be a colon-separated list of filenames.
  130. #          Expand $VARNAME at the start of its filenames.
  131. #          Let varname=0 and -option- turn off an option.
  132. # 96/05/05 Changed meaning of 7th arg to Opts; now can specify exactly how many
  133. #          of the vars should be searched for in the environment.
  134. #          Check for duplicate rcfiles.
  135. # 96/05/13 Return more specific error values.  Note: ProcArgs() and InitOpts()
  136. #          now return various negatives values on error, not just -1, and
  137. #          Opts() may set Err to various positive values, not just 1.
  138. #          Added AllowUnrecOpt.
  139. # 96/05/23 Check type given for & option
  140. # 96/06/15 Re-port to awk
  141. # 96/10/01 Moved file-reading code into ReadConfFile(), so that it can be
  142. #          used by other functions.
  143. # 96/10/15 Added OptChars
  144. # 96/11/01 Added exOpts arg to Opts()
  145. # 96/11/16 Added ; type
  146. # 96/12/08 Added Opt2Set() & Opt2Sets()
  147. # 96/12/27 Added CmdLineOpt()
  148.  
  149. # optlist is a string which contains all of the possible command line options.
  150. # A character followed by certain characters indicates that the option takes
  151. # an argument, with type as follows:
  152. # :    String argument
  153. # ;    Non-empty string argument
  154. # *    Floating point argument
  155. # (    Non-negative floating point argument
  156. # )    Positive floating point argument
  157. # #    Integer argument
  158. # <    Non-negative integer argument
  159. # >    Positive integer argument
  160. # The only difference the type of argument makes is in the runtime argument
  161. # error checking that is done.
  162.  
  163. # The & option is a special case used to get numeric options without the
  164. # user having to give an option character.  It is shorthand for [-+.0-9].
  165. # If & is included in optlist and an option string that begins with one of
  166. # these characters is seen, the value given to "&" will include the first
  167. # char of the option.  & must be followed by a type character other than ":"
  168. # or ";".
  169. # Note that if e.g. &> is given, an option of -.5 will produce an error.
  170.  
  171. # Strings in argv[] which begin with "-" or "+" are taken to be
  172. # strings of options, except that a string which consists solely of "-"
  173. # or "+" is taken to be a non-option string; like other non-option strings,
  174. # it stops the scanning of argv and is left in argv[].
  175. # An argument of "--" or "++" also stops the scanning of argv[] but is removed.
  176. # If an option takes an argument, the argument may either immediately
  177. # follow it or be given separately.
  178. # "-" and "+" options are treated the same.  "+" is allowed because most awks
  179. # take any -options to be arguments to themselves.  gawk 2.15 was enhanced to
  180. # stop scanning when it encounters an unrecognized option, though until 2.15.5
  181. # this feature had a flaw that caused problems in some cases.  See the OptChars
  182. # parameter to explicitly set the option-specifier characters.
  183.  
  184. # If an option that does not take an argument is given,
  185. # an index with its name is created in Options and its value is set to the
  186. # number of times it occurs in argv[].
  187.  
  188. # If an option that does take an argument is given, an index with its name is
  189. # created in Options and its value is set to the value of the argument given
  190. # for it, and Options[option-name,"count"] is (initially) set to the 1.
  191. # If an option that takes an argument is given more than once,
  192. # Options[option-name,"count"] is incremented, and the value is assigned to
  193. # the index (option-name,instance) where instance is 2 for the second occurance
  194. # of the option, etc.
  195. # In other words, the first time an option with a value is encountered, the
  196. # value is assigned to an index consisting only of its name; for any further
  197. # occurances of the option, the value index has an extra (count) dimension.
  198.  
  199. # The sequence number for each option found in argv[] is stored in
  200. # Options[option-name,"num",instance], where instance is 1 for the first
  201. # occurance of the option, etc.  The sequence number starts at 1 and is
  202. # incremented for each option, both those that have a value and those that
  203. # do not.  Options set from a config file have a value of 0 assigned to this.
  204.  
  205. # Options and their arguments are deleted from argv.
  206. # Note that this means that there may be gaps left in the indices of argv[].
  207. # If compress is nonzero, argv[] is packed by moving its elements so that
  208. # they have contiguous integer indices starting with 0.
  209. # Option processing will stop with the first unrecognized option, just as
  210. # though -- was given except that unlike -- the unrecognized option will not be
  211. # removed from ARGV[].  Normally, an error value is returned in this case.
  212. # If AllowUnrecOpt is true, it is not an error for an unrecognized option to
  213. # be found, so the number of remaining arguments is returned instead.
  214. # If OptChars is not a null string, it is the set of characters that indicate
  215. # that an argument is an option string if the string begins with one of the
  216. # characters.  A string consisting solely of two of the same option-indicator
  217. # characters stops the scanning of argv[].  The default is "-+".
  218. # argv[0] is not examined.
  219. # The number of arguments left in argc is returned.
  220. # If an error occurs, the global string OptErr is set to an error message
  221. # and a negative value is returned.
  222. # Current error values:
  223. # -1: option that required an argument did not get it.
  224. # -2: argument of incorrect type supplied for an option.
  225. # -3: unrecognized (invalid) option.
  226. function ProcArgs(argc,argv,OptList,Options,compress,AllowUnrecOpt,OptChars,
  227. ArgNum,ArgsLeft,Arg,ArgLen,ArgInd,Option,Pos,NumOpt,Value,HadValue,specGiven,
  228. NeedNextOpt,GotValue,OptionNum,Escape,dest,src,count,c,OptTerm,OptCharSet)
  229. {
  230. # ArgNum is the index of the argument being processed.
  231. # ArgsLeft is the number of arguments left in argv.
  232. # Arg is the argument being processed.
  233. # ArgLen is the length of the argument being processed.
  234. # ArgInd is the position of the character in Arg being processed.
  235. # Option is the character in Arg being processed.
  236. # Pos is the position in OptList of the option being processed.
  237. # NumOpt is true if a numeric option may be given.
  238.     ArgsLeft = argc
  239.     NumOpt = index(OptList,"&")
  240.     OptionNum = 0
  241.     if (OptChars == "")
  242.     OptChars = "-+"
  243.     while (OptChars != "") {
  244.     c = substr(OptChars,1,1)
  245.     OptChars = substr(OptChars,2)
  246.     OptCharSet[c]
  247.     OptTerm[c c]
  248.     }
  249.     for (ArgNum = 1; ArgNum < argc; ArgNum++) {
  250.     Arg = argv[ArgNum]
  251.     if (length(Arg) < 2 || !((specGiven = substr(Arg,1,1)) in OptCharSet))
  252.         break    # Not an option; quit
  253.     if (Arg in OptTerm) {
  254.         delete argv[ArgNum]
  255.         ArgsLeft--
  256.         break
  257.     }
  258.     ArgLen = length(Arg)
  259.     for (ArgInd = 2; ArgInd <= ArgLen; ArgInd++) {
  260.         Option = substr(Arg,ArgInd,1)
  261.         if (NumOpt && Option ~ /[-+.0-9]/) {
  262.         # If this option is a numeric option, make its flag be & and
  263.         # its option string flag position be the position of & in
  264.         # the option string.
  265.         Option = "&"
  266.         Pos = NumOpt
  267.         # Prefix Arg with a char so that ArgInd will point to the
  268.         # first char of the numeric option.
  269.         Arg = "&" Arg
  270.         ArgLen++
  271.         }
  272.         # Find position of flag in option string, to get its type (if any).
  273.         # Disallow & as literal flag.
  274.         else if (!(Pos = index(OptList,Option)) || Option == "&") {
  275.         if (AllowUnrecOpt) {
  276.             Escape = 1
  277.             break
  278.         }
  279.         else {
  280.             OptErr = "Invalid option: " specGiven Option
  281.             return -3
  282.         }
  283.         }
  284.  
  285.         # Find what the value of the option will be if it takes one.
  286.         # NeedNextOpt is true if the option specifier is the last char of
  287.         # this arg, which means that if the option requires a value it is
  288.         # the next arg.
  289.         if (NeedNextOpt = (ArgInd >= ArgLen)) { # Value is the next arg
  290.         if (GotValue = ArgNum + 1 < argc)
  291.             Value = argv[ArgNum+1]
  292.         }
  293.         else {    # Value is included with option
  294.         Value = substr(Arg,ArgInd + 1)
  295.         GotValue = 1
  296.         }
  297.  
  298.         if (HadValue = AssignVal(Option,Value,Options,
  299.         substr(OptList,Pos + 1,1),GotValue,"",++OptionNum,!NeedNextOpt,
  300.         specGiven)) {
  301.         if (HadValue < 0)    # error occured
  302.             return HadValue
  303.         if (HadValue == 2)
  304.             ArgInd++    # Account for the single-char value we used.
  305.         else {
  306.             if (NeedNextOpt) {    # option took next arg as value
  307.             delete argv[++ArgNum]
  308.             ArgsLeft--
  309.             }
  310.             break    # This option has been used up
  311.         }
  312.         }
  313.     }
  314.     if (Escape)
  315.         break
  316.     # Do not delete arg until after processing of it, so that if it is not
  317.     # recognized it can be left in ARGV[].
  318.     delete argv[ArgNum]
  319.     ArgsLeft--
  320.     }
  321.     if (compress != 0) {
  322.     dest = 1
  323.     src = argc - ArgsLeft + 1
  324.     for (count = ArgsLeft - 1; count; count--) {
  325.         ARGV[dest] = ARGV[src]
  326.         dest++
  327.         src++
  328.     }
  329.     }
  330.     return ArgsLeft
  331. }
  332.  
  333. # Assignment to values in Options[] occurs only in this function.
  334. # Option: Option specifier character.
  335. # Value: Value to be assigned to option, if it takes a value.
  336. # Options[]: Options array to return values in.
  337. # ArgType: Argument type specifier character.
  338. # GotValue: Whether any value is available to be assigned to this option.
  339. # Name: Name of option being processed.
  340. # OptionNum: Number of this option (starting with 1) if set in argv[],
  341. #     or 0 if it was given in a config file or in the environment.
  342. # SingleOpt: true if the value (if any) that is available for this option was
  343. #     given as part of the same command line arg as the option.  Used only for
  344. #     options from the command line.
  345. # specGiven is the option specifier character use, if any (e.g. - or +),
  346. # for use in error messages.
  347. # Global variables: OptErr
  348. # Return value: negative value on error, 0 if option did not require an
  349. # argument, 1 if it did & used the whole arg, 2 if it required just one char of
  350. # the arg.
  351. # Current error values:
  352. # -1: Option that required an argument did not get it.
  353. # -2: Value of incorrect type supplied for option.
  354. # -3: Bad type given for option &
  355. function AssignVal(Option,Value,Options,ArgType,GotValue,Name,OptionNum,
  356. SingleOpt,specGiven,  UsedValue,Err,NumTypes) {
  357.     # If option takes a value...    [
  358.     NumTypes = "*()#<>]"
  359.     if (Option == "&" && ArgType !~ "[" NumTypes) {    # ]
  360.     OptErr = "Bad type given for & option"
  361.     return -3
  362.     }
  363.  
  364.     if (UsedValue = (ArgType ~ "[:;" NumTypes)) {    # ]
  365.     if (!GotValue) {
  366.         if (Name != "")
  367.         OptErr = "Variable requires a value -- " Name
  368.         else
  369.         OptErr = "option requires an argument -- " Option
  370.         return -1
  371.     }
  372.     if ((Err = CheckType(ArgType,Value,Option,Name,specGiven)) != "") {
  373.         OptErr = Err
  374.         return -2
  375.     }
  376.     # Mark this as a numeric variable; will be propogated to Options[] val.
  377.     if (ArgType != ":" && ArgType != ";")
  378.         Value += 0
  379.     if ((Instance = ++Options[Option,"count"]) > 1)
  380.         Options[Option,Instance] = Value
  381.     else
  382.         Options[Option] = Value
  383.     }
  384.     # If this is an environ or rcfile assignment & it was given a value...
  385.     else if (!OptionNum && Value != "") {
  386.     UsedValue = 1
  387.     # If the value is "0" or "-" and this is the first instance of it,
  388.     # do not set Options[Option]; this allows an assignment in an rcfile to
  389.     # turn off an option (for the simple "Option in Options" test) in such
  390.     # a way that it cannot be turned on in a later file.
  391.     if (!(Option in Options) && (Value == "0" || Value == "-"))
  392.         Instance = 1
  393.     else
  394.         Instance = ++Options[Option]
  395.     # Save the value even though this is a flag
  396.     Options[Option,Instance] = Value
  397.     }
  398.     # If this is a command line flag and has a - following it in the same arg,
  399.     # it is being turned off.
  400.     else if (OptionNum && SingleOpt && substr(Value,1,1) == "-") {
  401.     UsedValue = 2
  402.     if (Option in Options)
  403.         Instance = ++Options[Option]
  404.     else
  405.         Instance = 1
  406.     Options[Option,Instance]
  407.     }
  408.     # If this is a flag assignment without a value, increment the count for the
  409.     # flag unless it was turned off.  The indicator for a flag being turned off
  410.     # is that the flag index has not been set in Options[] but it has an
  411.     # instance count.
  412.     else if (Option in Options || !((Option,1) in Options))
  413.     # Increment number of times this flag seen; will inc null value to 1
  414.     Instance = ++Options[Option]
  415.     Options[Option,"num",Instance] = OptionNum
  416.     return UsedValue
  417. }
  418.  
  419. # Option is the option letter
  420. # Value is the value being assigned
  421. # Name is the var name of the option, if any
  422. # ArgType is one of:
  423. # :    String argument
  424. # ;    Non-null string argument
  425. # *    Floating point argument
  426. # (    Non-negative floating point argument
  427. # )    Positive floating point argument
  428. # #    Integer argument
  429. # <    Non-negative integer argument
  430. # >    Positive integer argument
  431. # specGiven is the option specifier character use, if any (e.g. - or +),
  432. # for use in error messages.
  433. # Returns null on success, err string on error
  434. function CheckType(ArgType,Value,Option,Name,specGiven,  Err,ErrStr) {
  435.     if (ArgType == ":")
  436.     return ""
  437.     if (ArgType == ";") {
  438.     if (Value == "")
  439.         Err = "must be a non-empty string"
  440.     }
  441.     # A number begins with optional + or -, and is followed by a string of
  442.     # digits or a decimal with digits before it, after it, or both
  443.     else if (Value !~ /^[-+]?([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.)$/)
  444.     Err = "must be a number"
  445.     else if (ArgType ~ "[#<>]" && Value ~ /\./)
  446.     Err = "may not include a fraction"
  447.     else if (ArgType ~ "[()<>]" && Value < 0)
  448.     Err = "may not be negative"
  449.     # (
  450.     else if (ArgType ~ "[)>]" && Value == 0)
  451.     Err = "must be a positive number"
  452.     if (Err != "") {
  453.     ErrStr = "Bad value \"" Value "\".  Value assigned to "
  454.     if (Name != "")
  455.         return ErrStr "variable " substr(Name,1,1) " " Err
  456.     else {
  457.         if (Option == "&")
  458.         Option = Value
  459.         return ErrStr "option " specGiven substr(Option,1,1) " " Err
  460.     }
  461.     }
  462.     else
  463.     return ""
  464. }
  465.  
  466. # Note: only the above functions are needed by ProcArgs.
  467. # The rest of these functions call ProcArgs() and also do other
  468. # option-processing stuff.
  469.  
  470. # Opts: Process command line arguments.
  471. # Opts processes command line arguments using ProcArgs()
  472. # and checks for errors.  If an error occurs, a message is printed
  473. # and the program is exited.
  474. #
  475. # Input variables:
  476. # Name is the name of the program, for error messages.
  477. # Usage is a usage message, for error messages.
  478. # OptList the option description string, as used by ProcArgs().
  479. # MinArgs is the minimum number of non-option arguments that this
  480. # program should have, non including ARGV[0] and +h.
  481. # If the program does not require any non-option arguments,
  482. # MinArgs should be omitted or given as 0.
  483. # rcFiles, if given, is a colon-seprated list of filenames to read for
  484. # variable initialization.  If a filename begins with ~/, the ~ is replaced
  485. # by the value of the environment variable HOME.  If a filename begins with
  486. # $, the part from the character after the $ up until (but not including)
  487. # the first character not in [a-zA-Z0-9_] will be searched for in the
  488. # environment; if found its value will be substituted, if not the filename will
  489. # be discarded.
  490. # rcfiles are read in the order given.
  491. # Values given in them will not override values given on the command line,
  492. # and values given in later files will not override those set in earlier
  493. # files, because AssignVal() will store each with a different instance index.
  494. # The first instance of each variable, either on the command line or in an
  495. # rcfile, will be stored with no instance index, and this is the value
  496. # normally used by programs that call this function.
  497. # VarNames is a comma-separated list of variable names to map to options,
  498. # in the same order as the options are given in OptList.
  499. # If EnvSearch is given and nonzero, the first EnvSearch variables will also be
  500. # searched for in the environment.  If set to -1, all values will be searched
  501. # for in the environment.  Values given in the environment will override
  502. # those given in the rcfiles but not those given on the command line.
  503. # NoRCopt, if given, is an additional letter option that if given on the
  504. # command line prevents the rcfiles from being read.
  505. # See ProcArgs() for a description of AllowUnRecOpt and optChars, and
  506. # ExclusiveOptions() for a description of exOpts.
  507. # Special options:
  508. # If x is made an option and is given, some debugging info is output.
  509. # h is assumed to be the help option.
  510.  
  511. # Global variables:
  512. # The command line arguments are taken from ARGV[].
  513. # The arguments that are option specifiers and values are removed from
  514. # ARGV[], leaving only ARGV[0] and the non-option arguments.
  515. # The number of elements in ARGV[] should be in ARGC.
  516. # After processing, ARGC is set to the number of elements left in ARGV[].
  517. # The option values are put in Options[].
  518. # On error, Err is set to a positive integer value so it can be checked for in
  519. # an END block.
  520. # Return value: The number of elements left in ARGV is returned.
  521. # Must keep OptErr global since it may be set by InitOpts().
  522. function Opts(Name,Usage,OptList,MinArgs,rcFiles,VarNames,EnvSearch,NoRCopt,
  523. AllowUnrecOpt,optChars,exOpts,  ArgsLeft,e) {
  524.     if (MinArgs == "")
  525.     MinArgs = 0
  526.     ArgsLeft = ProcArgs(ARGC,ARGV,OptList NoRCopt,Options,1,AllowUnrecOpt,
  527.     optChars)
  528.     if (ArgsLeft < (MinArgs+1) && !("h" in Options)) {
  529.     if (ArgsLeft >= 0) {
  530.         OptErr = "Not enough arguments"
  531.         Err = 4
  532.     }
  533.     else
  534.         Err = -ArgsLeft
  535.     printf "%s: %s.\nUse -h for help.\n%s\n",
  536.     Name,OptErr,Usage > "/dev/stderr"
  537.     exit 1
  538.     }
  539.     if (rcFiles != "" && (NoRCopt == "" || !(NoRCopt in Options)) &&
  540.     (e = InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch)) < 0)
  541.     {
  542.     print Name ": " OptErr ".\nUse -h for help." > "/dev/stderr"
  543.     Err = -e
  544.     exit 1
  545.     }
  546.     if ((exOpts != "") && ((OptErr = ExclusiveOptions(exOpts,Options)) != ""))
  547.     {
  548.     printf "%s: Error: %s\n",Name,OptErr > "/dev/stderr"
  549.     Err = 1
  550.     exit 1
  551.     }
  552.     return ArgsLeft
  553. }
  554.  
  555. # ReadConfFile(): Read a file containing var/value assignments, in the form
  556. # <variable-name><assignment-char><value>.
  557. # Whitespace (spaces and tabs) around a variable (leading whitespace on the
  558. # line and whitespace between the variable name and the assignment character) 
  559. # is stripped.  Lines that do not contain an assignment operator or which
  560. # contain a null variable name are ignored, other than possibly being noted in
  561. # the return value.  If more than one assignment is made to a variable, the
  562. # first assignment is used.
  563. # Input variables:
  564. # File is the file to read.
  565. # Comment is the line-comment character.  If it is found as the first non-
  566. #     whitespace character on a line, the line is ignored.
  567. # Assign is the assignment string.  The first instance of Assign on a line
  568. #     separates the variable name from its value.
  569. # If StripWhite is true, whitespace around the value (whitespace between the
  570. #     assignment char and trailing whitespace on the line) is stripped.
  571. # VarPat is a pattern that variable names must match.  
  572. #     Example: "^[a-zA-Z][a-zA-Z0-9]+$"
  573. # If FlagsOK is true, variables are allowed to be "set" by being put alone on
  574. #     a line; no assignment operator is needed.  These variables are set in
  575. #     the output array with a null value.  Lines containing nothing but
  576. #     whitespace are still ignored.
  577. # Output variables:
  578. # Values[] contains the assignments, with the indexes being the variable names
  579. #     and the values being the assigned values.
  580. # Lines[] contains the line number that each variable occured on.  A flag set
  581. #     is record by giving it an index in Lines[] but not in Values[].
  582. # Return value:
  583. # If any errors occur, a string consisting of descriptions of the errors
  584. # separated by newlines is returned.  In no case will the string start with a
  585. # numeric value.  If no errors occur,  the number of lines read is returned.
  586. function ReadConfigFile(Values,Lines,File,Comment,Assign,StripWhite,VarPat,
  587. FlagsOK,
  588. Line,Status,Errs,AssignLen,LineNum,Var,Val) {
  589.     if (Comment != "")
  590.     Comment = "^" Comment
  591.     AssignLen = length(Assign)
  592.     if (VarPat == "")
  593.     VarPat = "."    # null varname not allowed
  594.     while ((Status = (getline Line < File)) == 1) {
  595.     LineNum++
  596.     sub("^[ \t]+","",Line)
  597.     if (Line == "")        # blank line
  598.         continue
  599.     if (Comment != "" && Line ~ Comment)
  600.         continue
  601.     if (Pos = index(Line,Assign)) {
  602.         Var = substr(Line,1,Pos-1)
  603.         Val = substr(Line,Pos+AssignLen)
  604.         if (StripWhite) {
  605.         sub("^[ \t]+","",Val)
  606.         sub("[ \t]+$","",Val)
  607.         }
  608.     }
  609.     else {
  610.         Var = Line    # If no value, var is entire line
  611.         Val = ""
  612.     }
  613.     if (!FlagsOK && Val == "") {
  614.         Errs = Errs \
  615.         sprintf("\nBad assignment on line %d of file %s: %s",
  616.         LineNum,File,Line)
  617.         continue
  618.     }
  619.     sub("[ \t]+$","",Var)
  620.     if (Var !~ VarPat) {
  621.         Errs = Errs sprintf("\nBad variable name on line %d of file %s: %s",
  622.         LineNum,File,Var)
  623.         continue
  624.     }
  625.     if (!(Var in Lines)) {
  626.         Lines[Var] = LineNum
  627.         if (Pos)
  628.         Values[Var] = Val
  629.     }
  630.     }
  631.     if (Status)
  632.     Errs = Errs "\nCould not read file " File
  633.     close(File)
  634.     return Errs == "" ? LineNum : substr(Errs,2)    # Skip first newline
  635. }
  636.  
  637. # Variables:
  638. # Data is stored in Options[].
  639. # rcFiles, OptList, VarNames, and EnvSearch are as as described for Opts().
  640. # Global vars:
  641. # Sets OptErr.  Uses ENVIRON[].
  642. # If anything is read from any of the rcfiles, sets READ_RCFILE to 1.
  643. function InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch,
  644. Line,Var,Pos,Vars,Map,CharOpt,NumVars,TypesInd,Types,Type,Ret,i,rcFile,
  645. fNames,numrcFiles,filesRead,Err,Values,retStr) {
  646.     split("",filesRead,"")    # make awk know this is an array
  647.     NumVars = split(VarNames,Vars,",")
  648.     TypesInd = Ret = 0
  649.     if (EnvSearch == -1)
  650.     EnvSearch = NumVars
  651.     for (i = 1; i <= NumVars; i++) {
  652.     Var = Vars[i]
  653.     CharOpt = substr(OptList,++TypesInd,1)
  654.     if (CharOpt ~ "^[:;*()#<>&]$")
  655.         CharOpt = substr(OptList,++TypesInd,1)
  656.     Map[Var] = CharOpt
  657.     Types[Var] = Type = substr(OptList,TypesInd+1,1)
  658.     # Do not overwrite entries from environment
  659.     if (i <= EnvSearch && Var in ENVIRON &&
  660.     (Err = AssignVal(CharOpt,ENVIRON[Var],Options,Type,1,Var,0)) < 0)
  661.         return Err
  662.     }
  663.  
  664.     numrcFiles = split(rcFiles,fNames,":")
  665.     for (i = 1; i <= numrcFiles; i++) {
  666.     rcFile = fNames[i]
  667.     if (rcFile ~ "^~/")
  668.         rcFile = ENVIRON["HOME"] substr(rcFile,2)
  669.     else if (rcFile ~ /^\$/) {
  670.         rcFile = substr(rcFile,2)
  671.         match(rcFile,"^[a-zA-Z0-9_]*")
  672.         envvar = substr(rcFile,1,RLENGTH)
  673.         if (envvar in ENVIRON)
  674.         rcFile = ENVIRON[envvar] substr(rcFile,RLENGTH+1)
  675.         else
  676.         continue
  677.     }
  678.     if (rcFile in filesRead)
  679.         continue
  680.     # rcfiles are liable to be given more than once, e.g. UHOME and HOME
  681.     # may be the same
  682.     filesRead[rcFile]
  683.     if ("x" in Options)
  684.         printf "Reading configuration file %s\n",rcFile > "/dev/stderr"
  685.     retStr = ReadConfigFile(Values,Lines,rcFile,"#","=",0,"",1)
  686.     if (retStr > 0)
  687.         READ_RCFILE = 1
  688.     else if (ret != "") {
  689.         OptErr = retStr
  690.         Ret = -1
  691.     }
  692.     for (Var in Lines)
  693.         if (Var in Map) {
  694.         if ((Err = AssignVal(Map[Var],
  695.         Var in Values ? Values[Var] : "",Options,Types[Var],
  696.         Var in Values,Var,0)) < 0)
  697.             return Err
  698.         }
  699.         else {
  700.         OptErr = sprintf(\
  701.         "Unknown var \"%s\" assigned to on line %d\nof file %s",Var,
  702.         Lines[Var],rcFile)
  703.         Ret = -1
  704.         }
  705.     }
  706.  
  707.     if ("x" in Options)
  708.     for (Var in Map)
  709.         if (Map[Var] in Options)
  710.         printf "(%s) %s=%s\n",Map[Var],Var,Options[Map[Var]] > \
  711.         "/dev/stderr"
  712.         else
  713.         printf "(%s) %s not set\n",Map[Var],Var > "/dev/stderr"
  714.     return Ret
  715. }
  716.  
  717. # OptSets is a semicolon-separated list of sets of option sets.
  718. # Within a list of option sets, the option sets are separated by commas.  For
  719. # each set of sets, if any option in one of the sets is in Options[] AND any
  720. # option in one of the other sets is in Options[], an error string is returned.
  721. # If no conflicts are found, nothing is returned.
  722. # Example: if OptSets = "ab,def,g;i,j", an error will be returned due to
  723. # the exclusions presented by the first set of sets (ab,def,g) if:
  724. # (a or b is in Options[]) AND (d, e, or f is in Options[]) OR
  725. # (a or b is in Options[]) AND (g is in Options) OR
  726. # (d, e, or f is in Options[]) AND (g is in Options)
  727. # An error will be returned due to the exclusions presented by the second set
  728. # of sets (i,j) if: (i is in Options[]) AND (j is in Options[]).
  729. # todo: make options given on command line unset options given in config file
  730. # todo: that they conflict with.
  731. function ExclusiveOptions(OptSets,Options,
  732. Sets,SetSet,NumSets,Pos1,Pos2,Len,s1,s2,c1,c2,ErrStr,L1,L2,SetSets,NumSetSets,
  733. SetNum,OSetNum) {
  734.     NumSetSets = split(OptSets,SetSets,";")
  735.     # For each set of sets...
  736.     for (SetSet = 1; SetSet <= NumSetSets; SetSet++) {
  737.     # NumSets is the number of sets in this set of sets.
  738.     NumSets = split(SetSets[SetSet],Sets,",")
  739.     # For each set in a set of sets except the last...
  740.     for (SetNum = 1; SetNum < NumSets; SetNum++) {
  741.         s1 = Sets[SetNum]
  742.         L1 = length(s1)
  743.         for (Pos1 = 1; Pos1 <= L1; Pos1++)
  744.         # If any of the options in this set was given, check whether
  745.         # any of the options in the other sets was given.  Only check
  746.         # later sets since earlier sets will have already been checked
  747.         # against this set.
  748.         if ((c1 = substr(s1,Pos1,1)) in Options)
  749.             for (OSetNum = SetNum+1; OSetNum <= NumSets; OSetNum++) {
  750.             s2 = Sets[OSetNum]
  751.             L2 = length(s2)
  752.             for (Pos2 = 1; Pos2 <= L2; Pos2++)
  753.                 if ((c2 = substr(s2,Pos2,1)) in Options)
  754.                 ErrStr = ErrStr "\n"\
  755.                 sprintf("Cannot give both %s and %s options.",
  756.                 c1,c2)
  757.             }
  758.     }
  759.     }
  760.     if (ErrStr != "")
  761.     return substr(ErrStr,2)
  762.     return ""
  763. }
  764.  
  765. # The value of each instance of option Opt that occurs in Options[] is made an
  766. # index of Set[].
  767. # The return value is the number of instances of Opt in Options.
  768. function Opt2Set(Options,Opt,Set,  count) {
  769.     if (!(Opt in Options))
  770.     return 0
  771.     Set[Options[Opt]]
  772.     count = Options[Opt,"count"]
  773.     for (; count > 1; count--)
  774.     Set[Options[Opt,count]]
  775.     return count
  776. }
  777.  
  778. # The value of each instance of option Opt that occurs in Options[] that
  779. # begins with "!" is made an index of nSet[] (with the ! stripped from it).
  780. # Other values are made indexes of Set[].
  781. # The return value is the number of instances of Opt in Options.
  782. function Opt2Sets(Options,Opt,Set,nSet,  count,aSet,ret) {
  783.     ret = Opt2Set(Options,Opt,aSet)
  784.     for (value in aSet)
  785.     if (substr(value,1,1) == "!")
  786.         nSet[substr(value,2)]
  787.     else
  788.         Set[value]
  789.     return ret
  790. }
  791.  
  792. # Returns true if option Opt was given on the command line.
  793. function CmdLineOpt(Options,Opt,  i) {
  794.     for (i = 1; (Opt,"num",i) in Options; i++)
  795.     if (Options[Opt,"num",i] != 0)
  796.         return 1
  797.     return 0
  798. }
  799. ### End of ProcArgs library
  800. ### Begin qsort routines
  801.  
  802. # Arr[] is an array of values with arbitrary indices.
  803. # k[] is returned with numeric indices 1..n.
  804. # The values in k[] are the indices of Arr[],
  805. # ordered so that if Arr[] is stepped through
  806. # in the order Arr[k[1]] .. Arr[k[n]], it will be stepped
  807. # through in order of the values of its elements.
  808. # The return value is the number of elements in the arrays (n).
  809. function qsortArbIndByValue(Arr,k,  ArrInd,ElNum) {
  810.     ElNum = 0
  811.     for (ArrInd in Arr)
  812.     k[++ElNum] = ArrInd
  813.     qsortSegment(Arr,k,1,ElNum)
  814.     return ElNum
  815. }
  816.  
  817. # Sort a segment of an array.
  818. # Arr[] contains data with arbitrary indices.
  819. # k[] has indices 1..nelem, with the indices of arr[] as values.
  820. # This function sorts the elements of arr that are pointed to by
  821. # k[start..end], swapping the values of elements of k[] so that
  822. # when this function returns arr[k[start..end]] will be in order.
  823. function qsortSegment(Arr,k,start,end,  left,right,sepval,tmp,tmpe,tmps) {
  824.     # handle two-element case explicitly for a tiny speedup
  825.     if ((end - start) == 1) {
  826.     if (Arr[tmps = k[start]] > Arr[tmpe = k[end]]) {
  827.         k[start] = tmpe
  828.         k[end] = tmps
  829.     }
  830.     return
  831.     }
  832.     # Make sure comparisons act on these as numbers
  833.     left = start+0
  834.     right = end+0
  835.     sepval = Arr[k[int((left + right) / 2)]]
  836.     # Make every element <= sepval be to the left of every element > sepval
  837.     while (left < right) {
  838.     while (Arr[k[left]] < sepval)
  839.         left++
  840.     while (Arr[k[right]] > sepval)
  841.         right--
  842.     if (left < right) {
  843.         tmp = k[left]
  844.         k[left++] = k[right]
  845.         k[right--] = tmp
  846.     }
  847.     }
  848.     if (left == right)
  849.     if (Arr[k[left]] < sepval)
  850.         left++
  851.     else
  852.         right--
  853.     if (start < right)
  854.     qsortSegment(Arr,k,start,right)
  855.     if (left < end)
  856.     qsortSegment(Arr,k,left,end)
  857. }
  858.  
  859. # Arr[] is an array of values with arbitrary indices.
  860. # k[] is returned with numeric indices 1..n.
  861. # The values in k are the indices of Arr[],
  862. # ordered so that if Arr[] is stepped through
  863. # in the order Arr[k[1]] .. Arr[k[n]], it will be stepped
  864. # through in order of the values of its indices.
  865. # The return value is the number of elements in the arrays (n).
  866. # If the indexes are numeric, Numeric should be true, so that they can be
  867. # compared as such rather than as strings.  Numeric indexes do not have to be
  868. # contiguous.
  869. function qsortByArbIndex(Arr,k,Numeric,  ArrInd,ElNum) {
  870.     ElNum = 0
  871.     if (Numeric)
  872.     # Indexes do not preserve numeric type, so must be forced
  873.     for (ArrInd in Arr)
  874.         k[++ElNum] = ArrInd+0
  875.     else
  876.     for (ArrInd in Arr)
  877.         k[++ElNum] = ArrInd
  878.     qsortNumIndByValue(k,1,ElNum)
  879.     return ElNum
  880. }
  881.  
  882. # Arr is an array of elements with contiguous numeric indexes to be sorted
  883. # by value.
  884. # start and end are the starting and ending indexes of the range to be sorted.
  885. function qsortNumIndByValue(Arr,start,end,  left,right,sepval,tmp,tmpe,tmps) {
  886.     # handle two-element case explicitly for a tiny speedup
  887.     if ((start - end) == 1) {
  888.     if ((tmps = Arr[start]) > (tmpe = Arr[end])) {
  889.         Arr[start] = tmpe
  890.         Arr[end] = tmps
  891.     }
  892.     return
  893.     }
  894.     left = start+0
  895.     right = end+0
  896.     sepval = Arr[int((left + right) / 2)]
  897.     while (left < right) {
  898.     while (Arr[left] < sepval)
  899.         left++
  900.     while (Arr[right] > sepval)
  901.         right--
  902.     if (left <= right) {
  903.         tmp = Arr[left]
  904.         Arr[left++] = Arr[right]
  905.         Arr[right--] = tmp
  906.     }
  907.     }
  908.     if (start < right)
  909.     qsortNumIndByValue(Arr,start,right)
  910.     if (left < end)
  911.     qsortNumIndByValue(Arr,left,end)
  912. }
  913.  
  914. ### End qsort routines
  915.